﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ExpressionTreeLib;
using Expression = System.Linq.Expressions.Expression;

namespace EditorExe.StepRequestDialogs
{
    /// <summary>
    /// Interaction logic for RequestParameters.xaml
    /// </summary>
    public partial class RequestParameters : Window, IStepRequest<ParameterExpression[]>
    {
        public RequestParameters()
        {
            InitializeComponent();
        }

        public bool Request(ref ParameterExpression[] input)
        {
            this.button1.Content = "Next";
            return LastRequest(ref input);
        }

        public bool LastRequest(ref ParameterExpression[] input)
        {
            var vms = this.CreateCollection(input);
            this.dataGrid1.ItemsSource = vms;
            if(this.ShowDialog() ?? false)
            {
                input = new ParameterExpression[vms.Count];
                for (int i = 0; i < vms.Count; i++)
                {
                    input[i] = vms[i].ToExpression();
                }

                return true;
            }

            return false;
        }

        private ObservableCollection<ParameterViewModel> CreateCollection(ParameterExpression[] input)
        {
            var vms = new ObservableCollection<ParameterViewModel>();
            foreach (var parameterExpression in input)
            {
                vms.Add(new ParameterViewModel(parameterExpression));
            }

            return vms;
        }

        class ParameterViewModel
        {
            public string Name { get; set; }

            [TypeConverter(typeof(TypeTypeConverter))]
            public Type DataType { get; set; }

            public ParameterViewModel(ParameterExpression parameterExpression)
            {
                this.Name = parameterExpression.Name;
                this.DataType = parameterExpression.Type;
            }

            public ParameterExpression ToExpression()
            {
                return Expression.Parameter(this.DataType, this.Name);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //TODO: validation here or put validation in xaml
            this.DialogResult = true;
            this.Close();
        }
    }
}
